package com.yc154.springmvc.web;

import com.yc154.springmvc.biz.ServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

@RestControllerAdvice
public class Exhandler {

    // 只要是控制器抛出该异常, 那么都会被该方法拦截
    @ExceptionHandler(ServiceException.class)
    Object handleServiceException(ServiceException e,
                                  HttpServletRequest request){
        if(request.getHeader("Accept").contains("json")){
            // 返回json
            Map res = Map.of("code", 0,
                    "msg", e.getMessage(),
                    "data", e.getData());
            return res;
        } else {
            // 表单请求
            // URL 地址不支持非西方文字, 所以要编码
            String msg = URLEncoder.encode(e.getMessage(), Charset.defaultCharset());
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("redirect:/msg.html?"+msg);
            return modelAndView;
        }
    }
}
